// 采购录入
import React from 'react';
import './addNewDevice.scss';
import { Row, Col, Button, Form , Select, Input, Table , DatePicker,Space,Radio, message,InputNumber,Upload  } from 'antd';
import cookie from 'react-cookies'
import {eqModelList, categoryList, addEqModel,addEqBuyInfo,getModelByEq} from '../../../api/deviceLibrary'
import {getUserListByMenu} from '../../../api/accountManage'
import { getAttach} from '../../../api/extra'
import {UploadOutlined} from '@ant-design/icons';
const { Option } = Select;

class addNewDevice extends React.Component {
	cpmForm = React.createRef();
    pmForm = React.createRef();
    state ={
        coal_list:[],
        cpmListShow:[],// 展示table
        cpmListSubmit:[], // 提交 buy_to_eq 
        eq_list:[],
        list:[],
        user_list:[],
        cate_id:'',
        eq_name: '', // 设备类型
        buy_u_name:'', // 采买人名字
        fileList:[],
        contract_attach:'', // 采购合同id
        contract_time:'',
        eq_info:[], //  根据设备 设备型号各种规格
        spec_info:[],
        eq_model:'', // 设备型号
        invoice_rate:''
    }
    componentWillMount(){
        this.columns = [
            {
                title: '序号',
                dataIndex: 'index',
                key: '1',
                align: 'center',
                render: (text,record,index) => `${index+1}`,
            },
            {
              title: '设备名称',
              dataIndex: 'eq_name',
              key: '2'
            },
            {
              title: '设备型号',
              dataIndex: 'eq_model',
              key: '3'
            },
            {
              title: '数量',
              key: '4',
              dataIndex: 'buy_count',
            },
            {
                title: '规格',
                key: '5',
                render:(object)=>{
                    let str = ''
                    for (const key in object) {
                        if (this.CheckChinese(key)) {
                            str += key + '-' + object[key] + ','
                        }
                    }
                    str = str.substr(0, str.length - 1)
                    return <span> {str} </span>
                }
            },
            {
                title: '采购价格',
                key: '6',
                dataIndex: 'buy_price',
                render:(buy_price)=>(<span>{buy_price} 元</span>)
            },
            {
                title: '操作',
                key: '7',
                render: (text, record, index) => <a onClick={this.deteleData.bind(this,text.qdID)}>删除</a>
            }
        ];
    }
    componentDidMount(){
        this.CGLRgetUserListByMenu()
        this.getcategoryList()
    }
    // 删除
    deteleData=(val)=>{
        let {cpmListSubmit,cpmListShow } = this.state
        let newArray = cpmListShow.filter(function (item) {
            return item.qdID != val;
        })
        let newArraySubmit = cpmListSubmit.filter(function (item) {
            return item.qdID != val;
        })
        this.setState({
            cpmListSubmit:newArraySubmit,
            cpmListShow:newArray
        })
    }
    // 设备型号列表
    mygetModelByEq=()=>{
        let {cate_id} = this.state
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'id':cate_id
        }
        getModelByEq(post_data).then(res=>{
            this.setState({
                eq_info:res.data.eq_info
            })
        })
    }
    // 设备列表
    getcategoryList=()=>{
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
        }
        categoryList(post_data).then(res=>{
            if(res.code == 0) {
                let newArray = []
                for (let index = 0; index < res.data.list.length; index++) {
                    for (let item = 0; item < res.data.list[index].eq_list.length; item++) {
                        newArray.push(res.data.list[index].eq_list[item])
                    }
                }
                this.setState({
                    eq_list:newArray
                })
            }  
        })
    }
    // 设备新增型号
    getaddEqModel=()=>{
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
        }
        addEqModel(post_data).then(res=>{
            if(res.code == 0){
                message.success('新增成功')
            } else {
                message.error('新增失败')
            }
        })
    }
    // 采买人列表
    CGLRgetUserListByMenu=()=>{
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            'menu_tag':'equipment_buy'
        }
        getUserListByMenu(post_data).then(res=>{
            this.setState({user_list:res.data.user_list})
        })
    }
    // 采买类型
    choseEquipmenttype=(cate_id, name) => {
        if(cate_id) {
            this.setState({cate_id, eq_name:name.children},()=>{
                    this.mygetModelByEq()
            })
        } else {
            this.setState({cate_id:'', eq_name:''})
        }
    }
    // 上传
    getUpLoadUrl = () => {
        const {fileList} = this.state
        const UpImgUrl = JSON.parse(sessionStorage.getItem('urlConfig')).attach.upload_url;
        const _this = this;
        const props = {
            showUploadList: true,
            customRequest(option) {
                const post_data = {
                    upUrl: UpImgUrl,
                    file: option.file,
                    file_type:2
                }
                getAttach(post_data).then(res => {
                    if(res.code == 0) {
                        message.success('上传文件成功')
                        _this.setState({contract_attach:res.data.attach_id})
                    } else {
                        message.error('上传文件失败')
                    }
                })
            },
            beforeUpload: file => {
                return new Promise((resolve, reject) => {
                    let fileName = file.name;
                    //截取文件名
                    let pointPos = fileName.indexOf('.');
                    fileName = fileName.substr(pointPos+1);
                    //判断文件是否符合正则表达式的规则
                    if (fileName.indexOf('pdf') == -1) {
                        message.error('上传类型必须为PDF文件')
                        return reject(false)
                     }
                    return resolve(true);
                  })
            },
            onChange({ fileList }) {
                _this.setState({ fileList, })
                let file = fileList[0]
                if(file) {
                    file.status = 'done'
                }
            },
            onRemove() {
                _this.setState({
                    fileList: []
                })
            }
        }
        return props;
    }
    // 验证是否是中文
    CheckChinese=(str)=> {
            var reg = new RegExp("[\\u4E00-\\u9FFF]+", "g");
            return reg.test(str)
    }
    // 添加采买内容
    onFinish=()=>{
            let {buy_count,buy_price,spec_value_color,spec_value_ram} = this.cpmForm.current.getFieldsValue()
            let {eq_name,eq_model,cpmListShow,cpmListSubmit,spec_info} = this.state
            if(!eq_name) {
                message.warn('请选择设备类型')
                return 
            }
            if(!eq_model) {
                message.warn('请选择设备型号')
                return 
            }
            if(!buy_count) {
                message.warn('请输入数量')
                return 
            }
            if(!buy_price) {
                message.warn('请输入采购价格')
                return 
            }
            let newObj = this.cpmForm.current.getFieldsValue()
            for (let key in newObj) {
                if(newObj[key] == undefined){
                    message.warn(`请选择${key}规格`)
                    return
                }
            }
            // 准备显示table
            newObj.spec_value_color= newObj['颜色']
            newObj.eq_name = eq_name
            newObj.qdID = cpmListShow.length
            newObj.eq_model = eq_model
            let newArray = [newObj, ...cpmListShow]
            // 准备提交table
            let clobj = JSON.parse(JSON.stringify(newObj))
            // 统计所有的汉字value
            clobj.spec_value = []
            for (let key in clobj) {
                if (this.CheckChinese(key)) {
                    clobj.spec_value.push(clobj[key])
                }
            }
            // 统计所有的汉字key值
            clobj.spec_key = []
            for (let index = 0; index < spec_info.length; index++) {
                clobj.spec_key.push(spec_info[index].spec_key)
            }
            let newSubmitArray = [clobj,...cpmListSubmit]
            this.setState({cpmListShow:newArray,cpmListSubmit:newSubmitArray,spec_info:[]}, ()=>{
                this.cpmForm.current.resetFields()
            })
    }
    // 采买人
    purchaser=(buy_u_id,name)=>{
        if(buy_u_id) {
            this.setState({buy_u_name:name.children})
        } else {
            this.setState({buy_u_name:''})
        }
    }
    // 返回
    goFOne=()=>{
        // 返回之前清空炒作
        // this.pmForm.current.resetFields()
        // this.cpmForm.current.resetFields()
        // this.props.history.go(-1)
        window.history.back()
    }
    checkKPDS=(val)=>{
        if (Number(val.target.value) > 100) {
            message.warn('开票点数不能超过100%！')
            return 
        }
        this.setState({invoice_rate:val.target.value})
    }
    // 提交
    SubimeForm=()=>{
        let {cpmListSubmit,contract_attach,contract_time,buy_u_name,invoice_rate} = this.state
        let {buy_u_id,contract_amount,contract_name,invoice_type} = this.pmForm.current.getFieldsValue()
        if(!contract_amount){
            message.warn('请输入合同金额！')
            return 
        }
        if(!contract_name){
            message.warn('请输入合同名称！')
            return 
        }
        if(invoice_type != 4){
            if(!invoice_rate){
                message.warn('请输入开票点数！')
                return 
            } else if (Number(invoice_rate) > 100) {
                message.warn('开票点数不能超过100%！')
                return
            }
        }
        
        if(!invoice_type){
            message.warn('请选择开票类型！')
            return 
        }
        if(!contract_time){
            message.warn('请输入合同时间')
            return 
        }
        if(!buy_u_id){
            message.warn('请选择采买人！')
            return 
        }
        if(cpmListSubmit.length == 0){
            message.warn('采买内容不能为空！')
            return 
        }
        // 上传id
        if(!contract_attach){
            message.warn('请上传合同!')
            return 
        }
        let post_data = {
            'auth_token': cookie.load('station_console_setting_web_login').auth_token,
            buy_u_id,
            buy_u_name,
            contract_amount,
            contract_name,
            invoice_rate,
            invoice_type,
            contract_time,
            contract_attach,
            'buy_to_eq':JSON.stringify(cpmListSubmit)
        }
        addEqBuyInfo(post_data).then(res=>{
            if(res.code == 0){
                message.success('添加成功')
                this.setState({
                    cpmListShow:[],// 展示table
                    cpmListSubmit:[], // 提交 buy_to_eq
                    eq_info:[], //  根据设备 设备型号各种规格
                    spec_info:[],
                    eq_model:'', // 设备型号
                    fileList:[],
                    cate_id:'',
                    eq_name: '', // 设备类型
                    buy_u_name:'', // 采买人名字
                })
                this.pmForm.current.resetFields()
            } else {
                message.error('添加失败')
            }
        })
    }
    onChangeTime = (value, dateString) => {
        this.setState({
            contract_time: dateString,
        })
    }
    // 循环
    choseItem=(val,val2)=>{
        // eq_model
        let {eq_info,eq_model} = this.state
        let newArr = eq_info.filter(function(params) {
            return params.spu_id == val
        })
        if(val){
            this.setState({spec_info:newArr[0].spec_info,eq_model:val2.children})
        } else {
            this.setState({spec_info:[],eq_model:''})
        }
    }
    render() {
        const {fileList,cpmListShow,eq_list,eq_info,user_list,spec_info} = this.state
        return (
            <div className="controlPancel_home">
                {/* 新增型号 */}
                 <Row className="finishedCoal">
                    <Col span={24}>
                        <div className="titleInfo">
                            <div></div>
                            <div><span>新增型号</span></div>
                        </div>
                        <div className="cb_form">
                            <Form  ref={this.pmForm} name="control-hooks" >
                                {/* 合同名称 */}
                                <Form.Item name="contract_name" label="合同名称" rules={[{ required: true,message: '请输入合同名称' }]} style={{width:500}}>
                                    <Input allowClear placeholder="请输入合同名称"/>
                                </Form.Item>
                                {/* 合同金额、合同时间 */}
                                <Row>
                                    <Col span={5}>
                                        <Form.Item name="contract_amount" label="合同金额" rules={[{ required: true,message: '请输入合同金额'}]} >
                                            <InputNumber style={{width:'100%'}} min={0}  allowClear   placeholder="请输入合同金额"/>
                                        </Form.Item>
                                    </Col>
                                    <Col span={8} offset={4}>
                                        <Form.Item name="contract_time" label="合同时间" style={{width:'100%'}} rules={[{ required: true,message: '请输入合同时间' }]}>
                                            <DatePicker  format="YYYY-MM-DD" onChange={this.onChangeTime.bind(this)}/>
                                        </Form.Item>
                                    </Col>
                                </Row>
                                {/* 开票类型、开票点数*/}
                                <Row>
                                    <Col span={5}>
                                        <Form.Item name="invoice_type" label="开票类型" rules={[{ required: true,message: '请选择开票类型'}]}>
                                            <Select placeholder="请选择开票类型"  allowClear>
                                                <Option value="1">增值税</Option>
                                                <Option value="2">普通</Option>
                                                <Option value="3">专业</Option>
                                                <Option value="4">不开票</Option>
                                            </Select>
                                        </Form.Item></Col>
                                    <Col span={5} offset={4}>
                                        <Form.Item name="invoice_rate" label="开票点数"  onChange={this.checkKPDS} className="iii iii2">
                                            <InputNumber style={{width:'93%'}} allowClear addonAfter="%" placeholder="请输入开票点数, 最多保持两位小数"/>%
                                        </Form.Item>
                                    </Col>
                                </Row>
                                {/* 采买人 */}
                                <Row>
                                    <Col span={5}>
                                        <Form.Item name="buy_u_id" label="采买人" rules={[{ required: true,message: '请选择采买人'}]} className="duyifen" >
                                            <Select placeholder="请选择采买人"  allowClear onChange={this.purchaser}>
                                                { user_list.map((val, ind) => ( <Option value={ val.uid } key={ val.uid }>{ val.user_name }</Option> ))}
                                            </Select>
                                        </Form.Item>
                                    </Col>
                                    <Col className="iii" span={5} offset={4}>
                                        <span>附件上传: </span>
                                        <Upload
                                            {...this.getUpLoadUrl()}
                                            showUploadList
                                            max={1}
                                            fileList={fileList}
                                            progress={false}
                                            >
                                               <Button disabled={fileList.length > 0} style={{padding:'10px 24px 28px 24px',borderRadius:'6px', marginLeft:6}} icon={<UploadOutlined />} >添加附件</Button>     
                                        </Upload>
                                    </Col>
                                </Row>
                            </Form>
                        </div>
                    </Col>
                 </Row>
                {/* 采买内容  */}
                <Row className="cb_information">
                    <Col span={24}>
                        <div className="titleInfo">
                            <div></div>
                            <div><span>采买内容</span></div>
                        </div>
                        <div className="cb_form">
                            <Form  ref={this.cpmForm} name="control-hooks" >
                                {/*  设备类型、设备型号、设备数量*/}
                                <Row>
                                    <Col span={10}>
                                        <Space  style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                            <div className="iii">设备类型: </div>
                                            <Form.Item
                                                name="cate_id"
                                                rules={[{ required: true, message: '请选择设备类型' }]}
                                                style={{width:'150px',backgroundColor:'#fff'}}
                                            >
                                                <Select placeholder="请选择设备类型"  allowClear onChange={this.choseEquipmenttype}>
                                                        { eq_list.map((val, ind) => ( <Option value={ val.id } key={ val.id }>{ val.cate_name }</Option> ))}
                                                </Select>
                                            </Form.Item>
                                            <span
                                                style={{ display: 'inline-block', width: '24px', lineHeight: '32px', textAlign: 'center' }}
                                            >
                                                -
                                            </span>
                                            <Form.Item
                                                name="spu_id"
                                                rules={[{ required: true, message: '请选择设备型号' }]}
                                                style={{width:'150px',backgroundColor:'#fff'}}
                                                >
                                                    <Select placeholder="请选择设备型号"  allowClear  onChange={this.choseItem}>
                                                            { eq_info.map((val, ind) => ( <Option value={ val.spu_id } key={ val.spu_id }>{ val.eq_model }</Option> ))}
                                                    </Select>
                                                </Form.Item>
                                        </Space> 
                                    </Col>
                                    <Col span={5} >
                                        <Form.Item 
                                            name="buy_count"  
                                            label="采购数量" 
                                            rules={[
                                                {
                                                    required: true,
                                                    message: '请输入设备采购数量',
                                                },
                                                ]}
                                            >
                                            <Input allowClear placeholder="请输入设备采购数量"/>
                                        </Form.Item>
                                    </Col>
                                </Row>
                                {/* 采购价格 */}
                                <Row>
                                    <Col span={5}>
                                        <Form.Item 
                                            name="buy_price"  
                                            label="采购价格"
                                            rules={[{
                                                required: true,
                                                message: '请输入设备采购金额',
                                            },
                                            ]}>
                                            <InputNumber style={{width:'100%'}} min={0} allowClear placeholder="请输入设备采购金额"/>
                                        </Form.Item>
                                    </Col>
                                </Row>
                                <Row>
                                {/* 设备规格 */}
                                <Col span={10} >
                                    <Space  style={{ display: 'flex', marginBottom: 8 }} align="baseline">
                                            <div className="iii">设备规格: </div>
                                            <div>
                                                { spec_info.map((item, ind) => (
                                                    // val.spec_info.map((item, ind) => (
                                                        <Form.Item
                                                                name={item.spec_key}
                                                                label={item.spec_key}
                                                                rules={[
                                                                {
                                                                    required: true,
                                                                    message: `请选择${item.spec_key}`,
                                                                },
                                                                ]}
                                                            >
                                                                <Radio.Group>
                                                                    { item.spec_value.map((ii,ind)=> (
                                                                        <Radio value={ii} style={{marginRight:8}}>{ii}</Radio>
                                                                    ))}
                                                                </Radio.Group>
                                                        </Form.Item>
                                                    // ))
                                                 ))}
                                            </div>
                                        </Space> 
                                    </Col>
                                </Row>
                                <Form.Item wrapperCol={15} style={{width:"100%"}} className="btn_ss" htmlType="submit">
                                         <Button type="primary" style={{float: 'right',marginRight: '10%',
                                        borderRadius: '4px',
                                        padding:'8px 24px 28px 24px',
                                        backgroundColor: '#334BFC'}} onClick={this.onFinish}>添加</Button>
                                </Form.Item>
                            </Form>
                        </div>
                    </Col>
                 </Row>
                {/* table */}
                <Row className="cb_report">
                    <Col span={24}>
                        <div className="cb_table">
                            <Table
                                columns={this.columns}
                                dataSource={cpmListShow}
                                bordered
                                pagination={false}
                            />
                        </div>
                    </Col>
                </Row>
                {/* 提交 */}
                <Row className="btn">
                    <Col span={24}>
                        <Button onClick={()=>window.location.href='/index/deviceLibrary/deviceBuy'}>取消</Button>
                        <Button type="primary" onClick={this.SubimeForm} style={{margin: '0 10px'}}>提交</Button>
                    </Col>
                </Row>
            </div>
        )
    }
}
export default addNewDevice;